import { DataSet } from 'choerodon-ui/pro';
import { devopsOrganizationsApi, pipelineTemplateApi, devopsProjectApi } from '@choerodon/master';
import { pipelinTemplateApiConfig } from '@/api';

const templateDataSet = new DataSet({
  autoQuery: false,
  transport: {
    read: () => ({
      ...pipelinTemplateApiConfig.getPipelineTemplate(),
      transformResponse: (res) => {
        let newRes = res;
        try {
          newRes = JSON.parse(newRes);
          return newRes?.ciTemplateCategoryDTOList;
        } catch (error) {
          return newRes?.ciTemplateCategoryDTOList;
        }
      },
    }),
  },
});

const Index = (level: any): any => ({
  autoCreate: true,
  fields: [{
    name: 'name',
    type: 'string',
    label: '流水线模板名称',
    required: true,
    validator: async (value: string, name: string, record: any) => {
      let checkRes = true;
      if (level === 'organization') {
        checkRes = await devopsOrganizationsApi.checkOrgPinelineName({
          name: value,
        });
      } else if (level === 'site') {
        checkRes = await pipelineTemplateApi.checkCreatePipelineName({ name: value });
      } else if (level === 'project') {
        checkRes = await devopsProjectApi.checkProjectPinelineName({ name: value });
      }
      if (!checkRes) {
        return '流水线模板名称必须唯一';
      }
      return checkRes;
    },
  }, {
    name: 'ciTemplateCategoryId',
    type: 'string',
    label: '流水线分类',
    required: true,
    defaultValue: '0',
    // 这里是按照后端的数据 给的默认值 customSelect好像不给默认值会出问题
    options: templateDataSet,
  }],
});

export default Index;

export { templateDataSet };
